//
//  SHRefreshControl.swift
//  下拉刷新
//
//  Created by 卫平玉 on 16/7/25.
//  Copyright © 2016年 卫平玉. All rights reserved.
//

import UIKit

private let RefreshControlH: CGFloat = 50

enum  SHRefreshControlState: Int{
    
    case Normal = 0
    
    case Pulling = 1
    
    case Refreshing = 2
}

class SHRefreshControl: UIControl {

    var shState: SHRefreshControlState = .Normal{
        
        didSet{
            
            switch shState {
                
            case .Normal:
//                messageLabel.text = "正常"
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.pullImageView.transform = CGAffineTransformIdentity
                })
                
                if oldValue == .Refreshing{
                    
                    UIView.animateWithDuration(0.25, animations: { () -> Void in
                        self.scrollView?.contentInset.top -= RefreshControlH
//                          print(self.scrollView?.contentInset.top)
                        }, completion: { (_) -> Void in
                            self.pullImageView.hidden = false
                            self.indicatorView.stopAnimating()
                    })
                }
                
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    
                    self.pullImageView.transform = CGAffineTransformIdentity
                })
                
            case .Pulling:
                messageLabel.text = "下拉中"
                
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    //旋转180°
                    self.pullImageView.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                })
            case .Refreshing:
                pullImageView.hidden = true
                indicatorView.startAnimating()
                messageLabel.text = "刷新中"
                
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.scrollView?.contentInset.top += RefreshControlH
//                      print(self.scrollView?.contentInset.top)
                    }, completion: { (_) -> Void in
                        
                        self.sendActionsForControlEvents(UIControlEvents.ValueChanged)
                })
                
            }
        }
    }
    
    var scrollView: UIScrollView?
    
    override init(frame: CGRect) {
        super.init(frame: CGRectMake(0, -RefreshControlH,  SCREENW, RefreshControlH))
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func endRefreshing(){
        
        shState = .Normal
    }
    
    override func willMoveToSuperview(newSuperview: UIView?) {
        
        guard let scrollView = newSuperview as? UIScrollView else{
            return
        }
        
        self.scrollView = scrollView
        
        self.scrollView?.addObserver(self, forKeyPath: "contentOffset", options: NSKeyValueObservingOptions.New, context: nil)
    }
    
    
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
        getSHRefreshControlState(self.scrollView?.contentOffset.y)
    }
    
    func getSHRefreshControlState(contentOffsetY: CGFloat?){
        //-64
        let contentIntSetTop = self.scrollView?.contentInset.top ?? 0

        if self.scrollView!.dragging{
            
            if contentOffsetY > -RefreshControlH - contentIntSetTop && shState == .Pulling{
                shState = .Normal
            }else if contentOffsetY <= -RefreshControlH - contentIntSetTop && shState == .Normal{
                //偏移了114而且此时的状态为正常，那么它就进入下拉状态
                shState = .Pulling
            }
        }else{
            
            if shState == .Pulling{
                
                shState = .Refreshing
            }
        }
    }

    private func setupUI(){
        
        backgroundColor = UIColor.brownColor()
        
        addSubview(messageLabel)
        
        addSubview(indicatorView)
        
        addSubview(pullImageView)
//        messageLabel.snp_makeConstraints { (make) -> Void in
//            make.centerY.equalTo(self)
//        }
//        
//        indicatorView.snp_makeConstraints { (make) -> Void in
//            make.centerX.equalTo(self).offset(-35)
//            make.centerY.equalTo(self)
//        }
//        
//        pullImageView.snp_makeConstraints { (make) -> Void in
//            make.centerX.equalTo(self).offset(-35)
//            make.centerY.equalTo(self)
//        }
        messageLabel.translatesAutoresizingMaskIntoConstraints = false
     
        addConstraint(NSLayoutConstraint(item: messageLabel, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0))
        
        addConstraint(NSLayoutConstraint(item: messageLabel, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0))
        
        indicatorView.translatesAutoresizingMaskIntoConstraints = false
        addConstraint(NSLayoutConstraint(item: indicatorView, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: -35))
        addConstraint(NSLayoutConstraint(item: indicatorView, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0))
        
        pullImageView.translatesAutoresizingMaskIntoConstraints = false
        addConstraint(NSLayoutConstraint(item: pullImageView, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: pullImageView, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: -35))
    }
    
    private lazy var messageLabel: UILabel = {
        let lab = UILabel()
//        lab.text = "正常"
        lab.textColor = UIColor.whiteColor()
        lab.font = UIFont.systemFontOfSize(15)
        return lab
    }()
    
    private lazy var indicatorView: UIActivityIndicatorView = {
        let view = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.White)
        return view
    }()
    
    private lazy var pullImageView: UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    
    
    deinit{
        
        self.removeObserver(self, forKeyPath: "contentOffset")
    }
    
    
    
    
}
